<template>
  <el-container class="sop_tas">
    <el-main>
      <el-card shadow="never" class="selectCard searchColumn">
        <el-form label-position="right" label-width="6rem">
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="任务名称：">
                <el-input v-model="searchParams.name" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8" style="float: right;">
              <search-button :default-params="searchParams" @refreshParams="refreshParams" @getList="getList1" />
            </el-col>
          </el-row>

        </el-form>
      </el-card>
      <el-card shadow="never" class="commercia-tenant-list-title tableCard">
        <vxe-toolbar>
          <template v-slot:buttons>
            <el-button type="primary" icon="el-icon-plus" size="small" @click="openModal('', 1, false)">新增任务</el-button>
          </template>
          <template v-slot:tools>
            <vxe-button class="tool-btn" type="text" size="small" icon="el-icon-refresh" @click="getList()">刷新</vxe-button>
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTable"
          border
          resizable
          show-overflow
          highlight-hover-row
          :loading="loading"
          :auto-resize="true"
          :data="dataList"
          width
          max-height="420"
          :print-config="{}"
          header-align="center"
        >
          <vxe-table-column type="seq" align="center" width="50" title=" " />
          <vxe-table-column field="name" title="任务名称" min-width="220" />
          <vxe-table-column field="sendEmployee" title="执行员工" min-width="220" />
          <vxe-table-column field="sendScope" title="发送客户" min-width="220" />
          <vxe-table-column field="sendStatusDesc" width="80" align="center" title="状态" />
          <vxe-table-column field="sendTime" width="120" title="下达时间" />
          <vxe-table-column title="操作" fixed="right" width="150" align="center" slots="default">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="openModal(scope.row.id, 2, true)">查看</el-button>
              <el-button v-if="scope.row.status != 1" type="text" size="mini" @click="openModal(scope.row.id, 2, false)">编辑</el-button>
              <el-button v-if="scope.row.status != 1" type="text" size="mini" @click="del(scope.row.id)">删除</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
          :current-page.sync="pageNum"
          :page-size.sync="pageSize"
          :total="total"
          :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          @page-change="getList()"
        />
      </el-card>
    </el-main>
    <el-dialog v-if="dialogVisible" width="65%" title="任务编辑" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form ref="ruleForm" :model="params" :rules="rules" label-width="6rem">
        <el-row :gutter="40">
          <el-col :span="24">
            <el-form-item prop="name" label="任务名称：">
              <el-input v-model="params.name" :disabled="diabledEdit" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="remark" label="任务描述：">
              <el-input v-model="params.remark" :disabled="diabledEdit" type="textarea" rows="2" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="sendRule" label="执行员工：">
              <div style="display: inline-block;justify-content: flex-start;width: 100%;">
                <div style="display: inline-flex; padding-left: 20px;background: #f8f8f8;width: 100%;vertical-align: middle;">
                  <div style="vertical-align: middle;margin-top: 5px;">
                    <vxe-button type="info" size="small" icon="el-icon-plus" style="margin-top: 10px;" @click="selectEmployee()">添加员工</vxe-button>
                  </div>
                  <div v-if="selectedEmployeeList.length >0" style="margin: 10px;background: #fcfcfc;border: 1px solid #d5d5d5;width:80%;">
                    <el-tag v-for="(tag, index) in selectedEmployeeList" :key="index" type="" hit="true" effect="plain" closable="true" style="margin-left:5px;margin-bottom: 5px;cursor: pointer;" @close="closeEmployeeTag(index)">{{ tag.employeeNameCn }}</el-tag>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="sendRule" label="发送客户：">
              <div style="display: inline-block;justify-content: flex-start;width: 100%;">
                <div>
                  <el-radio-group v-model="params.msgSendRule.isAllFriends" size="small">
                    <el-radio :label="1">全部客户</el-radio>
                    <el-radio :label="2">条件筛选</el-radio>
                  </el-radio-group>
                </div>
                <div v-if="params.msgSendRule.isAllFriends === 2" style="display: inline-flex; padding-left: 20px;background: #f8f8f8;width: 100%;vertical-align: middle;">
                  <div>
                    <vxe-button type="info" size="small" icon="el-icon-plus" style="margin-top: 10px;" @click="selectFriendsTags()">标签选择</vxe-button>
                  </div>
                  <div v-if="selectedTagsList.length >0" style="margin: 10px;background: #fcfcfc;border: 1px solid #d5d5d5;width: 100%;">
                    <el-tag v-for="(tag, index) in selectedTagsList" :key="index" type="" hit="true" effect="plain" closable="true" style="margin-left:5px;margin-bottom: 5px;cursor: pointer;" @close="closeTag(index)">{{ tag.tagsName }}</el-tag>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-tabs v-model="currentTab" type="card" editable @tab-add="handleAddTabs" @tab-remove="handleRemoveTabs">
              <el-tab-pane v-for="(tabItem, tabIndex) in params.fansMomentSopDetails" :key="tabIndex" :label="tabItem.tabTitle" :name="tabItem.tabTitle" closable>
                <el-row :gutter="40">
                  <el-col :span="14">
                    <el-form-item prop="sendName" label="发送时间：">
                      <div style="display: flex; justify-content: flex-start;">
                        <span style="width: 45%;">
                          <el-date-picker v-model="tabItem.sendDate" type="date" placeholder="选择日期" :disabled="diabledEdit" size="small" format="yyyy-MM-dd" value-format="yyyy-MM-dd" @change="(value) => changeSendDate(value, tabIndex)" />
                        </span>
                        <span style="margin-left: 10px;">发送时间：</span>
                        <span style="width: 35%;">
                          <el-time-picker v-model="tabItem.sendTime" placeholder="时间选择" size="small" value-format="HH:mm:ss" format="HH:mm:ss" :disabled="diabledEdit" />
                        </span>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item prop="sendName" label="发送标题：">
                      <el-input v-model="tabItem.sendName" :disabled="diabledEdit" size="small" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item prop="content" label="消息内容：">
                      <div style="display: inline-block;width: 100%;" class="inputDeep">
                        <el-input id="templateContent" v-model="tabItem.content" type="textarea" :rows="8" maxlength="1000" show-word-limit resize="none" :disabled="diabledEdit" size="small" />
                        <div style="display: inline-block;">
                          <div style="display: flex; justify-content: flex-start;">
                            <div v-if="!diabledEdit" style="display: flex;">
                              <el-popover placement="top" width="380" trigger="click">
                                <div class="function-cont" style="margin-left: 10px; justify-content: center;">
                                  <el-row :gutter="10">
                                    <el-col :span="4">
                                      <div style="justify-content: center;display: inline-block;" @click="uploadImage(tabIndex)">
                                        <i class="el-icon-picture" style="cursor: pointer;position: relative;padding-left: 3px;" /><div style="font-size: 12px; cursor: pointer;">图片</div>
                                      </div>
                                    </el-col>
                                    <el-col :span="4" :offset="1">
                                      <div class="infoItem_editor_add" @click="uploadVideo(tabIndex)">
                                        <i class="el-icon-document" style="cursor: pointer;position: relative;padding-left: 3px;" /><div style="font-size: 12px;cursor: pointer;">视频</div>
                                      </div>
                                    </el-col>
                                    <el-col :span="4" :offset="1">
                                      <div class="infoItem_editor_add" @click="uploadFile(tabIndex)">
                                        <i class="el-icon-goods" style="cursor: pointer;position: relative;padding-left: 3px;" /><div style="font-size: 12px;cursor: pointer;">文件</div>
                                      </div>
                                    </el-col>
                                    <el-col :span="4" :offset="1" @click="uploadLink(tabIndex)">
                                      <div class="infoItem_editor_add">
                                        <i class="el-icon-sell" style="cursor: pointer;position: relative;padding-left: 3px;" /><div style="font-size: 12px;cursor: pointer;">链接</div>
                                      </div>
                                    </el-col>
                                    <el-col :span="5" @click="uploadWxMa(tabIndex)">
                                      <div class="infoItem_editor_add">
                                        <i class="el-icon-chat-dot-round" style="cursor: pointer;position: relative;padding-left: 10px;" /><div style="font-size: 12px;cursor: pointer;">小程序</div>
                                      </div>
                                    </el-col>
                                  </el-row>
                                </div>
                                <span slot="reference" style="font-size: 10px;color: cornflowerblue; cursor: pointer;"><i class="el-icon-plus">添加:图片/视频/文件/图文/小程序</i></span>
                              </el-popover>
                            </div>
                            <div class="function-cont" style="display: block; justify-content: right; margin-left: 10px; text-align: right;"><span style="font-size: 10px;">(备注：最多9个附件)</span></div>
                          </div>
                          <div class="file-url">
                            <div v-for="(item, index) in tabItem.attachements" :key="index" class="fz20 file-url-cont">
                              <div>
                                <span>{{ index+1 }}.</span>
                                <span @click="downFileClick(item.filePath)">{{ item.fileName }}</span>
                                <i v-if="!diabledEdit" class="el-icon-close" @click="closeFileClick(index)" />
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
    <ImgSource ref="imgSelect" :max="99999" @getUrl="getReturnPicsUrl" />
    <VideoSource ref="videoSelect" :max="99999" @getUrl="getReturnVideoUrl" />
    <DocSource ref="docSelect" :max="99999" @getUrl="getReturnDocUrl" />
    <EmployeeSelect ref="employeeSelect" :choose-list="chooseList" @getSelectedRecords="getReturnEmployeeRecords" />
    <FriendsTagsSelect ref="friendsTagsSelect" :choose-list="chooseList" @getSelectedRecords="getReturnRecords" />
  </el-container>
</template>

<script>
import { delFansMomentSop, getFansMomentSopPageList, addFansMomentSop, modifyFansMomentSop, viewFansMomentSop } from '@/api/cop/message'
import SearchButton from '@/components/SearchButton'
import ImgSource from './components/imgSelect'
import VideoSource from './components/videoSelect'
import DocSource from './components/docSelect'
import EmployeeSelect from './components/employeeSelect'
import FriendsTagsSelect from './components/friendsTagsSelect'
export default {
  components: {
    SearchButton,
    ImgSource,
    VideoSource,
    DocSource,
    EmployeeSelect,
    FriendsTagsSelect
  },
  data() {
    return {
      selectedEmployeeList: [],
      selectedTagsList: [],
      chooseList: [],
      dataList: [],
      loading: false,
      searchParams: {
        name: ''
      },
      pageNum: 1,
      pageSize: 20,
      total: 0,
      params: {
        name: '',
        important: 1,
        overtime: 1,
        remark: '',
        fansMomentSopDetails: [],
        msgSendRule: {
          isAllFriends: 1,
          employeeCodeList: [],
          friendsTagsList: []
        }
      },
      dialogVisible: false,
      diabledEdit: true,
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      parentId: '',
      currentTabIndex: '',
      currentTab: '',
      defaultDateTime: new Date(),
      operType: 1 // 1 添加 2修改
    }
  },
  created() {
    this.getList()
  },
  methods: {
    selectEmployee() {
      this.$refs.employeeSelect.dialog = true
    },
    selectFriendsTags() {
      this.$refs.friendsTagsSelect.dialog = true
    },
    closeTag(index) {
      this.selectedTagsList.splice(index, 1)
      this.params.msgSendRule.friendsTagsList.splice(index, 1)
    },
    uploadVideo(index) {
      this.currentTabIndex = index
      this.$refs.videoSelect.dialog = true
    },
    uploadFile(index) {
      this.currentTabIndex = index
      this.$refs.docSelect.dialog = true
    },
    uploadLink() {

    },
    uploadWxMa() {

    },
    uploadImage(index) {
      this.currentTabIndex = index
      this.$refs.imgSelect.dialog = true
    },
    getReturnPicsUrl(selectedPics) {
      var detailParams = this.params.fansMomentSopDetails[this.currentTabIndex]
      if (detailParams.attachements.length >= 9) {
        alert('最多可以添加9个附件，不能再增加了')
        return false
      }
      selectedPics.forEach(url => {
        const fullUrl = url.split('/')
        const fileName = fullUrl[fullUrl.length - 1]
        const formItem = detailParams.attachements.find(dd => dd.fileName === fileName)
        if (formItem === null || formItem === undefined) {
          detailParams.attachements.push({ filePath: url, fileName: fileName, msgType: 'image' })
        }
      })
    },
    getReturnDocUrl(url) {
      var detailParams = this.params.fansMomentSopDetails[this.currentTabIndex]
      if (detailParams.attachements.length >= 9) {
        alert('最多可以添加9个附件，不能再增加了')
        return false
      }
      if (url) {
        const fullUrl = url.split('/')
        const fileName = fullUrl[fullUrl.length - 1]
        const formItem = detailParams.attachements.find(dd => dd.fileName === fileName)
        if (formItem === null || formItem === undefined) {
          detailParams.attachements.push({ filePath: url, fileName: fileName, msgType: 'file' })
        }
      }
    },
    getReturnVideoUrl(url) {
      var detailParams = this.params.fansMomentSopDetails[this.currentTabIndex]
      if (detailParams.attachements.length >= 9) {
        alert('最多可以添加9个附件，不能再增加了')
        return false
      }
      if (url) {
        const fullUrl = url.split('/')
        const fileName = fullUrl[fullUrl.length - 1]
        const formItem = detailParams.attachements.find(dd => dd.fileName === fileName)
        if (formItem === null || formItem === undefined) {
          detailParams.attachements.push({ filePath: url, fileName: fileName, msgType: 'video' })
        }
      }
    },
    closeFileClick(i) {
      var detailParams = this.params.fansMomentSopDetails[this.currentTabIndex]
      this.$delete(detailParams.attachements, i)
    },
    downFileClick(filePath) {
      window.open(filePath, '_blank')
    },
    getReturnRecords(tagsRecords) {
      if (tagsRecords) {
        tagsRecords.forEach((item, index) => {
          this.selectedTagsList.push(item)
          this.params.msgSendRule.friendsTagsList.push(item.id)
        })
      }
    },
    getReturnEmployeeRecords(tagsRecords) {
      if (tagsRecords) {
        tagsRecords.forEach((item, index) => {
          this.selectedEmployeeList.push(item)
          this.params.msgSendRule.employeeCodeList.push(item.id)
        })
      }
    },
    closeEmployeeTag(index) {
      this.selectedEmployeeList.splice(index, 1)
      this.params.msgSendRule.employeeCodeList.splice(index, 1)
    },
    openModal(id, type, bool) {
      this.diabledEdit = bool
      this.operType = type
      this.dialogVisible = true
      if (type === 2) {
        viewFansMomentSop({ id })
          .then(response => {
            if (response) {
              this.params = response
              this.params.msgSendRule = response.msgSendRule
              this.params.msgSendRule.isAllFriends = response.msgSendRule.isAllFriends
              this.params.msgSendRule.friendsTagsList = response.msgSendRule.friendsTagsList
              this.params.msgSendRule.employeeCodeList = response.msgSendRule.employeeCodeList
              this.params.fansMomentSopDetails = response.fansMomentSopDetails
              if (this.params.fansMomentSopDetails) {
                this.currentTab = this.params.fansMomentSopDetails[0].tabTitle
              }
            }
          })
      } else {
        this.params.name = ''
        this.params.important = 1
        this.params.overtime = 1
        this.params.remark = ''
        this.params.msgSendRule = {
          isAllFriends: 1,
          friendsTagsList: [],
          employeeCodeList: []
        }
        const newTabName = 'Tab1'
        this.params.fansMomentSopDetails = [
          {
            tabTitle: newTabName,
            sendName: '',
            content: '',
            sendDate: '',
            sendTime: '',
            attachements: []
          }
        ]
        this.currentTab = newTabName
      }
    },
    getList() {
      getFansMomentSopPageList({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ... this.searchParams
      }).then(response => {
        if (response) {
          this.dataList = response.records
          this.total = response.total
        }
      })
    },
    submit() {
      var flag = 0
      if (this.params && this.params.fansMomentSopDetails) {
        this.params.fansMomentSopDetails.forEach(d => {
          if (d.sendDate === undefined || d.sendDate === null || d.sendDate === '') {
            alert('发送日期不能为空，请设置！')
            flag = 1
          }
          if (d.sendTime === undefined || d.sendTime === null || d.sendTime === '') {
            alert('发送时间不能为空，请设置！')
            flag = 1
          }
        })
      }
      if (flag === 1) {
        return
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.operType === 1) {
            addFansMomentSop(this.params).then(response => {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            modifyFansMomentSop(this.params).then(response => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    del(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delFansMomentSop({ id }).then(response => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    handleAddTabs(targetName) {
      var tabs = this.params.fansMomentSopDetails
      const newIndex = tabs.length + 1
      const newTabName = 'tab' + newIndex
      tabs.push({
        sendName: '',
        content: '',
        tabTitle: newTabName,
        sendDate: '',
        sendTime: '',
        attachements: []
      })
      this.currentTab = newTabName
    },
    handleRemoveTabs(targetName) {
      var tabs = this.params.fansMomentSopDetails
      let activeName = this.currentTab

      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.tabTitle === targetName) {
            var nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.tabTitle
            }
            if (tabs.length > 1) {
              tabs.splice(index, 1)
            }
          }
        })
      }
      this.currentTab = activeName
    },
    changeSendDate(val, tabIndex) {
      var tabs = this.params.fansMomentSopDetails
      var flag = 0
      tabs.forEach((tab, index) => {
        if (tab.tabTitle === val) {
          alert('该日期已经存在，请重新选择！')
          flag = 1
          return
        }
      })
      if (flag === 0) {
        var tab = tabs[tabIndex]
        tab.tabTitle = val
        this.currentTab = val
      }
    }
  }
}
</script>

<style lang="scss">
.sop_tas {
.function-cont{
    display: inline-flex;
    position: relative;
    flex-direction: row;
    flex-wrap: wrap;
    padding-left: 10px;
    justify-content: space-between;
     >div{
      width: 60px;
      display: inline-flex;
      text-align: center;
      justify-content: center;
      align-content: center;
      padding-bottom: 15px;
      line-height: 35px;
      border: 1px solid grey;
      >div{
        &:first-child{
          background: lightsteelblue;
          padding: 10px;
          cursor: pointer;
          margin-left: 10px;
          border: 1px solid grey;
          font-size: 10px;
          &::before{
            font-size: 40px;
            justify-content: center;
            color: #fff;
          }
        }
        &:last-child{
          cursor: pointer;
          justify-content: center;
          font-size: 14px;
        }
      }
     }
  }
  .inputDeep {
    :deep(.el-textarea__inner) {
      box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
      resize: none;
      cursor: default;
    }
  }
  .infoItem_editor_add {
      display: inline-block;
      padding-bottom: 1px;
      flex-direction: column;
      width: 80px;
      height: 80px;
      margin-left: 5px;
      border: 1px solid #dfe1e3;
      justify-content: center;
      float: right;
      text-align: center;
      align-items: center;
      align-content: center;
      font-size: 12px;
      cursor: pointer;
      margin-right: 5px;
      overflow: hidden;
      position: relative;
  }
  .info-form>>>.el-form-item label:after {
    content: " ";
    display: inline-block;
    width: 100%;
  }
  .info-form>>>.el-form-item__label {
    text-align: center;
    vertical-align: middle;
  }
  .info-form>>>.el-form-item.is-required .el-form-item__label:before {
    content: none !important;
  }
  .file-url{
    display: flex;
    line-height: 18px;
    flex-direction: column;
    .file-url-cont{
      div{
        padding: 2px;
        display: inline-block;
        cursor: pointer;
        span{
          margin-left: 10px;
          margin-right: 10px;
          float: left;
        }
        i {
          float: left;
          display: block;
          padding-top: 1px;
        }
        &:hover{
          background: #f5f7fa;
          i{
            display: block;
          }
        }
      }
   }
  }
}
</style>
